$(document).ready(function () {
    Carousel.memo = {
        enumName: "programTypeData",
        listName: "mockData",
        fatherId: 0,
        getChannel: "getChannel",
        contentType: "ContentType",
        getChannelList: "getChannelList",
        yesterdayEndTime: 0
    }
    Carousel.Dao = (function () {
        var cache = {};

        function getDataByName(targetName) {
            var responseData = Carousel.ajaxManager.findResponseData(targetName);
            return responseData;
        }

        function getChannel() {
            return getDataByName(Carousel.memo.getChannel).data;
        }

        function liveProgramType() {
            return getDataByName(Carousel.memo.enumName);
        }

        function getContentType() {
            return getDataByName(Carousel.memo.contentType);
        }

        function getFromCache(dataKey) {
            return cache[dataKey]
        }

        function putToCache(dataKey, data) {
            cache[dataKey] = data
        }

        return {
            getChannel: getChannel,
            liveProgramType: liveProgramType,
            getContentType: getContentType,
            getFromCache: getFromCache,
            putToCache: putToCache
        }

    })();
    Carousel.Formatter = (function () {
        function quickDateFormat(startTime) {
            return startTime.getFullYear() + "-" +
                (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
        }

        function reutrnNull() {
            // return "unknown"
            return "";
        }

        function formatDate(myDate) {
            var year = myDate.getFullYear();
            var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
            var day = ("0" + myDate.getDate()).slice(-2);
            var h = ("0" + myDate.getHours()).slice(-2);
            var m = ("0" + myDate.getMinutes()).slice(-2);
            var s = ("0" + myDate.getSeconds()).slice(-2);
            return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
        }

        function getFormatCopyRightEndTime(checkValue) {
            if (checkValue == null) {
                return reutrnNull();
            }
            if (typeof( checkValue ) == "string") {
                return checkValue;
            }
            if (checkValue <= 0) {
                return "---";
            } else {
                var date = new Date();
                date.setTime(parseInt(checkValue))
                return  formatDate(date);
            }
        }

        function getFormatPurchase(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                case -100:
                    return "免费";
                case 1:
                    return "收费";
                default:
                    return checkValue + ""
            }
        }

        function getFormatPublishStatus(checkValue) {
            if (checkValue == null)
                return reutrnNull();
            switch (checkValue) {
                case 0:
                    return "未发布";
                case 1:
                    return "已发布";
                case 2:
                    return "页面下线";
                case 3:
                    return "页面备用"
                default:
                    return checkValue + "";
            }
        }

        function getTemplate(item) {
            var formatArr = [];
            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
            formatArr.push('<span class="contract-width120">' + getFormatCopyRightEndTime(item.copyrightEndTime) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPurchase(item.isPurchase) + '</span>');
            formatArr.push('<span class="contract-width80">' + getFormatPublishStatus(item.pagePublishStatus) + '</span>');
            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
         //   return  Program.Util.template.albumSuggest( [item["id"],item["label"],item["channelName"],getFormatCopyRightEndTime(item.copyrightEndTime),getFormatPurchase(item.isPurchase),getFormatPublishStatus(item.pagePublishStatus)]  )
        }

        return {
            copyRight: getFormatCopyRightEndTime,
            publishStatus: getFormatPublishStatus,
            purchase: getFormatPurchase,
            getTemplate: getTemplate,
            quickDateFormat: quickDateFormat,
            formatDate: formatDate
        }
    })();
    Carousel.Validate = (function () {
        var reg1 = /^\d+$/;
        var reg3 = /^[1-9]\d*$/;
        var reg2 = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;

        function checkNum(checkString) {
            return reg1.test(checkString)
        }

        function checkPositive(checkString) {
            return reg3.test(checkString)
        }

        function checkDateFormat(checkString) {
            return reg2.test(checkString)
        }

        function defaultHandler(msg) {
            showTips({content: msg});
        }

        function batchCheck(checkArr) {
            if (checkArr == null) {
                checkArr = [];
            }
            if (checkArr.length == 0) {
                return true;
            }
            var flag = false;
            $.each(checkArr, function (index, checkData) {
                flag = baseCheck(checkData);
                if (!flag) {
                    return false;
                }
            })
            return flag;
        }

        function baseCheck(checkData) {
            var flag = false;
            if (!(checkData.value instanceof Array)) {
                checkData.value = [checkData.value];
            }
            if (!(checkData.error instanceof Array)) {
                checkData.error = [checkData.error];
            }
            if (checkData.handler == null) {
                checkData.handler = defaultHandler;
            }

            $.each(checkData.value, function (index, checkValue) {
                switch (checkData.type) {
                    case "date":
                        flag = checkDateFormat(checkValue);
                        break;
                    case "not_empty":
                        flag = checkValue != null && checkValue != "";
                        break;
                    case "eq":
                        flag = checkValue == checkData.other;
                        break;
                    case "ne":
                        flag = checkValue != checkData.other;
                        break;
                    case "gt":
                        flag = checkValue > checkData.other;
                        break;
                    case "ge":
                        flag = checkValue >= checkData.other;
                        break;
                    case "lt":
                        flag = checkValue < checkData.other;
                        break;
                    case "le":
                        flag = checkValue <= checkData.other;
                        break;
                    case "positive":
                        flag = checkPositive(checkValue)
                        break;
                    case "number":
                        flag = checkNum(checkValue)
                        break;
                    case "endsWith":
                        flag = checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                        break;
                    default :
                        break;
                }
                if (!flag) {
                    var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                    checkData.handler(hint);
                    return false;
                }
            })
            return flag
        }

        return {
            baseCheck: baseCheck,
            batchCheck: batchCheck,
            checkNum: checkNum
        }
    })();
    Carousel.Task = (function () {
        function sendDaySortTaskCallFunc(data) {
            showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
            if (data.code == "A00000") {
                $("#list").trigger("reloadGrid")
            }
        }

        function sendDaySortTask() {
            return {
                regName: "sendDaySort",
                options: {
                    url: Carousel.urlConfig.programDaySortUrl,
                    type: "post",
                    dataType: "json",
                    data: {fatherId: Carousel.memo.fatherId, sortDate: Carousel.memo.dataTime + " 00:00:00"},
                    success: function (data) {
                        sendDaySortTaskCallFunc(data);
                    },
                    error: function (data) {
                        console.log("data" + JSON.stringify(data));
                    }
                }
            }
        }

        function sendMoveTaskCallFunc(data) {
            showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
            if (data.code == "A00000") {
                $("#list").trigger("reloadGrid")
            }
        }

        function sendMoveTask(sendObj) {
            return {
                regName: "sendMoveTask",
                options: {
                    url: Carousel.urlConfig.programMoveUrl,
                    type: "post",
                    dataType: "json",
                    data: sendObj,
                    success: function (data) {
                        sendMoveTaskCallFunc(data);
                    },
                    error: function (data) {
                        console.log("data" + JSON.stringify(data));
                    }
                }
            }
        }

        function sendToggleLockTaskCallFunc(data) {
            showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
            if (data.code == "A00000") {
                $("#list").trigger("reloadGrid")
            }
        }

        function sendToggleLockTask(sendObj) {
            var self = this;
            self.lockType = sendObj.lockType;
            return {
                regName: "sendToggleLockTask",
                options: {
                    url: Carousel.urlConfig.programToggleLockUrl,
                    type: "post",
                    dataType: "json",
                    data: sendObj,
                    success: function (data) {
                        sendToggleLockTaskCallFunc(data);
                    },
                    error: function (data) {
                        console.log("data" + JSON.stringify(data));
                    }
                }
            }
        }

        function getContentTypeTask() {
            return {
                regName: Carousel.memo.contentType,
                options: {
                    type: "get",
                    url: Carousel.urlConfig.configs,
                    dataType: "json",
                    data: {type: Carousel.memo.contentType}
                }
            }
        }

        function getLiveProgramTypeTask() {
            return {
                regName: Carousel.memo.enumName,
                options: {
                    type: "get",
                    url: Carousel.urlConfig.configs,
                    dataType: "json",
                    data: {type: "LiveProgramType"}
                }
            }
        }

        return {
            sendMoveTask: sendMoveTask,
            sendDaySortTask: sendDaySortTask,
            sendToggleLockTask: sendToggleLockTask,
            getContentTypeTask: getContentTypeTask,
            getLiveProgramTypeTask: getLiveProgramTypeTask
        }
    })()

    Carousel.DialogManager = (function () {
        function initLoadLegoDlg() {
            $("#loadLegoMessage").dialog({
                title: "数据加载",
                autoOpen: false,
                width: 300,
                modal: true,
                dialogClass: 'alert',
                resizable: false
            });
        }

        function initDelMessageDlg() {
            $("#delMessage").dialog({
                title: "数据删除",
                autoOpen: false,
                width: 300,
                modal: true,
                dialogClass: 'alert',
                resizable: false,
                buttons: {
                    "ok": function () {
                        $(this).dialog("close");
                    },
                    "cancel": function () {
                        $(this).dialog("close");
                    }
                }
            });
        }

        function initDialogs() {
            initDelMessageDlg();
            initLoadLegoDlg();
            //   initAddProgramViewDlg();
            $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
        }

        function initDialogCall() {
            $("button[name=btn_auto_sort]").bind("click", function (event) {
                console.log("wait to deal");
                var selectedId = $("#list").jqGrid("getGridParam", "selrow")
                console.log(" selectedId " + selectedId);
                var selectedData = $("#list").jqGrid('getRowData', selectedId);
                console.log("selectedData:" + JSON.stringify(selectedData));
                Carousel.Grid.gridSort();
            })
            $("button[name=btn_insert]").bind("click", function (event) {
                var selectedId = $("#list").jqGrid("getGridParam", "selrow")
                var toHref = "/epg/carousel_insert.html?fatherId=" + Carousel.memo.fatherId;
                console.log(" selectedId " + selectedId);
                var currentDay = Carousel.Formatter.formatDate(new Date())
                var startTime = null;
                if (selectedId != null) {
                    var selectedData = $("#list").jqGrid('getRowData', selectedId);
                    startTime = selectedData.endPlayTime;
                    if (selectedData.endPlayTime.substr(0, 10) > selectedData.startPlayTime.substr(0, 10)) {
                        showTips({content: "不能选择跨天节目的结束时间!", type: "error"})
                        return
                    }
                } else {
                    startTime = Carousel.memo.dataTime + " 00:00:00";
                }
                if (currentDay.substr(0, 10) > startTime.substr(0, 10)) {
                    showTips({content: "插入天数不能小于操作天数", type: "error"})
                    return;
                }
                toHref += "&startTime=" + startTime;
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = toHref;
                el.target = '_blank'
                el.click();
                document.body.removeChild(el);
            })
            $("button[name=btn_auto_rule]").bind("click", function (event) {
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = "/epg/carousel_rule.html?fatherId=" + Carousel.memo.fatherId;
                el.target = '_blank';
                el.click();
                document.body.removeChild(el);
            })
            $("button[name=btn_automation_rule]").bind("click", function (event) {
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = "/epg/carousel_automation_rule.html?fatherId=" + Carousel.memo.fatherId;
                el.target = '_blank';
                el.click();
                document.body.removeChild(el);
            })

            ///epg/config_manager.html
            auth.getAuthData({tips: 1, url: '/epg/config_manager.html'}, function (rt) {
                if (rt) {
                    return;
                }
                $("button[name=btn_search_config]").show();
                $("button[name=btn_search_config]").bind("click", function (event) {
                    var el = document.createElement("a");
                    document.body.appendChild(el);
                    el.href = "/epg/config_manager.html?id=" + Carousel.memo.fatherId;
                    el.target = '_blank';
                    el.click();
                    document.body.removeChild(el);
                });
            });
        }

        return {
            initDialogs: initDialogs,
            initDialogCall: initDialogCall
        }
    })();

    Carousel.Operation = (function () {
        var entity = this;
        this.entityPath = "";
        this.tableName = "";
        function programBatchDel(entityArr) {
            if (entityArr.length == 0) {
                return
            }
            auth.getAuthData({tips: 1, url: '/epg/carousel_program_delete.html'}, function (rt) {
                if (rt) {
                    showTips({content: '很抱歉，您没有删除的权限!', type: "error"})
                    return;
                }
                SystemDialog.queryConfirm("确认删除？", function (flag) {
                    if (flag === true) {
                        $.ajax({
                            url: Carousel.urlConfig.programBatchDelUrl,
                            dataType: "json",
                            data: {ids: "[" + entityArr.join(",") + "]", dateTime: Carousel.memo.dataTime, channelId: Carousel.memo.fatherId},
                            beforeSend: function (request) {
                                request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                            },
                            type: "post",
                            success: function (data) {
                                SystemDialog.queryAlert(data.msg);
                                if (data.code == "A00000") {
                                    $("#list").trigger("reloadGrid");
                                }
                            },
                            error: function (data) {
                                if (data != null && data.msg != null) {
                                    SystemDialog.queryAlert(data.msg);
                                }
                                $("#list").trigger("reloadGrid");
                            }
                        })
                    }
                })
            });
        }

        function programDel(entityId) {
            auth.getAuthData({tips: 1, url: '/epg/carousel_program_delete.html'}, function (rt) {
                if (rt) {
                    showTips({content: '很抱歉，您没有删除的权限!', type: "error"})
                    return;
                }
                SystemDialog.queryConfirm("确认删除？", function (flag) {
                    if (flag === true) {
                        $.ajax({
                            url: Carousel.urlConfig.programDel,
                            dataType: "json",
                            data: {id: entityId},
                            beforeSend: function (request) {
                                request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                            },
                            type: "post",
                            success: function (data) {
                                SystemDialog.queryAlert(data.msg);
                                if (data.code == "A00000") {
                                    $("#list").trigger("reloadGrid")

                                }
                            },
                            error: function (data) {
                                if (data != null && data.msg != null) {
                                    SystemDialog.queryAlert(data.msg);
                                }
                                $("#list").trigger("reloadGrid");
                            }
                        })
                    }
                })
            });
        }

        function programMoveUp(entityId) {
            var sendData = {fatherId: Carousel.memo.fatherId, id: entityId, flag: 1, operationDay: Carousel.memo.dataTime};
            console.log("programMoveUp, wait to do" + JSON.stringify(sendData))
            submitMove(sendData);
        }

        //startPlayTime
        //endPlayTime
        function programMoveDown(entityId) {
            var sendData = {fatherId: Carousel.memo.fatherId, id: entityId, flag: 2, operationDay: Carousel.memo.dataTime};
            console.log("programMoveUp, wait to do" + JSON.stringify(sendData))
            submitMove(sendData);
        }

        function programToggleLock(entityId, lockType) {
            var sendData = {fatherId: Carousel.memo.fatherId, id: entityId, lockType: lockType };
            console.log("programToggleLock, wait to do" + JSON.stringify(sendData));
            submitToggleLock(sendData);
        }

        function programEdit(entityId) {
            var currentUrl = window.location.toString();
            var index = currentUrl.indexOf("program_list.html");
            var openUrl = currentUrl.substr(0, index) + "program_edit.html?id=" + entityId + "&from=carousel&fatherId=" + Carousel.memo.fatherId;
            window.open(openUrl);
        }

        function broadcast(entityId) {
            var currentUrl = window.location.toString();
            var index = currentUrl.indexOf("program_list.html");
            var openUrl = currentUrl.substr(0, index) + "broadcast_manager_episode.html?programId=" + entityId + "&id=" + Carousel.memo.fatherId;
            window.open(openUrl);
        }

        function submitToggleLock(data) {
            var task = Carousel.Task.sendToggleLockTask(data);
            Carousel.ajaxManager.push(task.regName, task.options, null, true);
            Carousel.ajaxManager.startLoad();
        }

        function submitMove(moveArr) {
            var task = Carousel.Task.sendMoveTask(moveArr);
            Carousel.ajaxManager.push(task.regName, task.options, null, true);
            Carousel.ajaxManager.startLoad();
        }

        function programIndexMove(curId, aimId) {
            console.log("curId:" + curId);
            console.log("aimId:" + aimId);
            $.ajax({
                url: Carousel.urlConfig.programIndexMoveUrl,
                dataType: "json",
                data: {id: curId, aimId: aimId, dateTime: Carousel.memo.dataTime, channelId: Carousel.memo.fatherId},
                beforeSend: function (request) {
                    request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                },
                type: "post",
                success: function (data) {
                    if (data.code == "A00000") {
                        $("#list").trigger("reloadGrid")
                    } else if (data.msg != null) {
                        SystemDialog.queryAlert(data.msg)
                        $("#list").trigger("reloadGrid")
                    }
                },
                error: function (data) {
                    if (data != null && data.msg != null) {
                        SystemDialog.queryAlert(data.msg);
                    }
                    $("#list").trigger("reloadGrid");
                }
            })
        }

        return {
            programMoveUp: programMoveUp,
            programMoveDown: programMoveDown,
            programDel: programDel,
            programEdit: programEdit,
            submitMove: submitMove,
            programBatchDel: programBatchDel,
            programIndexMove: programIndexMove,
            programToggleLock: programToggleLock,
            broadcast: broadcast
        }
    })()

    Carousel.Grid = (function () {
        var durationMap = null;
        var lockFlag = false;

        function fillLineNo() {
            var _jqGrid = $("#list");
            var dataOriginl = _jqGrid.jqGrid("getDataIDs");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            $.each(dataOriginl, function (i, element) {
                _jqGrid.setRowData(element, {"index": i + 1});
            })
            console.log("更新行号");
        }

        function mySelectedHandler(event) {
            var checkedFlag1 = $(event.currentTarget).prop("checked") == true;
            var _jqGrid = $("#list");
            var dataOriginl = Carousel.Dao.getFromCache("originalArr");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            var checkBoxArr = _jqGrid.find("input[type=checkbox][name^=jqg_list_]");
            $.each(checkBoxArr, function (i, element) {
                if ($(element).prop("disabled") != true && $(element).prop("checked") != checkedFlag1) {
                    _jqGrid.setSelection(dataOriginl[i].id, checkedFlag1);
                }
            });
            $(event.currentTarget).prop("checked", checkedFlag1)
        }

        function checkSelectAble(dataOriginl) {
            var _jqGrid = $("#list");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            var target = $("#cb_list");
            target.unbind();
            target.bind("click", mySelectedHandler);
            var currentDay = new Date();
            currentDay.setTime(currentDay.getTime() + 30 * 60 * 1000)
            //  currentDay.setTime(currentDay.getTime() - 30*60*1000 + 86400000 )
            var checkTime = Carousel.Formatter.formatDate(currentDay)
            $.each(dataOriginl, function (i, element) {
                if (element.startPlayTime < checkTime) {
                    _jqGrid.find("input[type=checkbox][name=jqg_list_" + element.id + "]").prop("disabled", "disabled");
                    // $("#"+element.id).prop("disabled", "disabled");
                    //   _jqGrid.find("input[type=checkbox][name=jqg_list_"+element.id+"]").parent().find("td[aria-describedby=list_index]").unbind();
                }

            });
        }

        function setColorTime(dataOriginl) {
            var aimGrid = $("#list");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            var checkLength = dataOriginl.length - 1;
            var check2 = null;
            var makeStartColor = [];
            var makeEndColor = [];
            var makeMockColor = [];
            $.each(dataOriginl, function (i, element) {
                if (element.qipuId == 0 && element.live == 1 && element.pname.indexOf("delete") == -1) {
                    makeMockColor.push(element.id);
                }
                if (i == checkLength) {
                    if (element.endPlayTime.length != 19 || "23:59:59" != element.endPlayTime.slice(-8)) {
                        if (element.endPlayTime.substr(0, 10) == element.startPlayTime.substr(0, 10)) {
                            makeEndColor.push(element.id);
                        }
                    }
                    return true;
                }
                check2 = dataOriginl[i + 1];

                if (element.endPlayTime > check2.startPlayTime) {
                    makeEndColor.push(element.id);
                    makeStartColor.push(check2.id);
                } else if (check2.startPlayTime > element.endPlayTime) {
                    makeStartColor.push(check2.id);
                }

                if (Carousel.memo.yesterdayEndTime > element.endPlayTime) {
                    makeEndColor.push(element.id);
                    makeStartColor.push(element.id);
                } else if (Carousel.memo.yesterdayEndTime > element.startPlayTime) {
                    makeStartColor.push(element.id);
                }
            });
            if (makeMockColor.length > 0) {
                var dealArr = [];
                $.each(makeMockColor, function (i, elementId) {
                    aimGrid.setCell(elementId, "startPlayTime", '', {color: "#00cccc"});
                    aimGrid.setCell(elementId, "endPlayTime", '', {color: "#00cccc"})
                })
            }

            if (makeStartColor.length > 0) {
                $.each(makeStartColor, function (i, elementId) {
                    aimGrid.setCell(elementId, "startPlayTime", '', {color: "#ff0000"});
                })
            }
            if (makeEndColor.length > 0) {
                $.each(makeEndColor, function (i, elementId) {
                    aimGrid.setCell(elementId, "endPlayTime", '', {color: "#ff0000"});
                })
            }
        }

        function addBreakHint(dataOriginl) {
            var aimGrid = $("#list");
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            $.each(durationMap, function (i, element) {
                if (element.duration > element.endPlayTime - element.startPlayTime) {
                    aimGrid.setCell(element.id, "endPlayTime", '', {backgroundColor: "#FFFF00"});
                }
            });
        }

        function gridSort() {
            var task = Carousel.Task.sendDaySortTask();
            Carousel.ajaxManager.push(task.regName, task.options, null, true);
            Carousel.ajaxManager.startLoad();
        }


        function recordDuration(dataOriginl) {
            durationMap = [];
            if (dataOriginl == null || dataOriginl.length == 0) {
                return;
            }
            $.each(dataOriginl, function (i, element) {
                var makeUpData = {};
                makeUpData.id = element.id
                makeUpData.referQipuId = element.carouselEpisode;
                makeUpData.isLive = element.live;
                makeUpData.startPlayTime = new Date(element.startPlayTime.replace(/-/g, "/")).getTime()
                makeUpData.endPlayTime = new Date(element.endPlayTime.replace(/-/g, "/")).getTime();
                makeUpData.pname = element.pname;
                if (makeUpData.isLive == 2) {
                    makeUpData.duration = makeUpData.endPlayTime - makeUpData.startPlayTime;
                } else {
                    makeUpData.duration = element.duration == null ? 0 : element.duration * 1000;
                }
                durationMap.push(makeUpData);
            })

        }

        function showNoResult(dataLength) {
            var jqGridTarget = $("#list");
            var parentElement = jqGridTarget.parent();
            if (parentElement.find(".norecords").html() == null) {
                parentElement.append('<div class="norecords">没有符合数据</div>');
                parentElement.find(".norecords").hide();
            }
            if (dataLength == 0) {
                parentElement.find(".norecords").show();
            } else {
                parentElement.find(".norecords").hide();
            }
        }

        function getBroadcastControl(rowObject) {
            if (rowObject.qipuId == 0) {
                return "<a class='disabled'>播控中心</a> ";
            }
            var element = Carousel.Dao.getChannel();
            var hasStream = false;
            if (element != null && element.menuShow != null) {
                hasStream = JSON.parse(element.menuShow).stream == 1;
                console.log("element.menuShow:" + element.menuShow);
            }
            if (hasStream) {
                return "<a href='#' onclick='Carousel.Operation.broadcast(" + rowObject.id + ")'>播控中心</a>  ";
            } else {
                return "<a class='disabled'>播控中心</a> ";
            }
        }

        function initProgramListGrid() {
            var listSize = 500;
            if (Com.url.getParameter("listSize") != null) {
                listSize = parseInt(Com.url.getParameter("listSize")) || 500;
            }

            var currentClient = Carousel.Formatter.formatDate(new Date());
            var _jqGrid = $("#list").jqGrid({
                loadBeforeSend: function (xhr, settings) {
                    xhr.setRequestHeader("Sign", "#f93Uc31K24()_@");
                    return true;
                },
                beforeProcessing: function (gdata, status, xhr) {
                    var listData = gdata.data;
                    var filterResult = listData.result;
                    $.ajax({
                        type: "post",
                        url: Carousel.urlConfig.yesterdayEndTimeUrl,
                        beforeSend: function (request) {
                            request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                        },
                        dataType: "json",
                        data: {channelId: Carousel.memo.fatherId, newStartTime: new Date((Carousel.memo.dataTime + " 00:00:00").replace(/-/g, "/")).getTime()  },
                        success: function (data) {
                            if (data.code === "A00000") {
                                Carousel.memo.yesterdayEndTime = Carousel.Formatter.formatDate(new Date(data.data));
                                console.log(" Carousel.memo.yesterdayEndTime:" + Carousel.memo.yesterdayEndTime);
                            }
                            Carousel.Dao.putToCache("originalArr", filterResult);
                            var rest = listData.totalCount % listData.pageSize;
                            listData.totalPages =  (listData.totalCount -rest )/listData.pageSize + (rest == 0 ? 0:1);
                            var fillData = {"total": listData.totalPages, "page": listData.pageNo, "records": listData.totalCount, "rows": filterResult};
                            $("#list")[0].addJSONData(fillData);
                            showNoResult(fillData.rows.length);
                            recordDuration(filterResult);
                            setColorTime(filterResult);
                            addBreakHint(filterResult);
                            fillLineNo();
                            checkSelectAble(filterResult);
                        }
                    })
                    return false;
                },
                jsonReader: {
                    id: "id",
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records"
                },
                cellEdit: true,
                cellsubmit: 'clientArray',
                afterSaveCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log("afterSaveCell value:" + value);
                    var dataOriginal = Carousel.Dao.getFromCache("originalArr");
                    var targetElement = dataOriginal[value - 1];
                    console.log("id" + rowid + ";aimid" + targetElement.id);
                    Carousel.Operation.programIndexMove(rowid, targetElement.id);
                },
                //   cellurl: Carousel.urlConfig.programIndexMoveUrl,
                afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                    var inputCell = $("#list").find("input[name=index]");
                    inputCell.focusout(function (event) {
                        setTimeout(function () {
                            var e = jQuery.Event("keydown");
                            e.keyCode = 13;
                            $(event.currentTarget).trigger(e);
                        }, 100)
                    });
                },
                loadComplete: function () {
                    var jqGridTarget = $("#list");
                    var re_records = jqGridTarget.getGridParam('records');
                    var parentElement = jqGridTarget.parent()
                    showNoResult((re_records == 0 || re_records == null) ? 0 : 1);
                },
                beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log(" beforeEditCell ");
                    var currentDay = new Date();
                    currentDay.setTime(currentDay.getTime() + 30 * 60 * 1000)
                    var checkTime = Carousel.Formatter.formatDate(currentDay);
                    var jqGridTarget = $("#list");
                    var element = jqGridTarget.getRowData(rowid);
                    var hiddenData = JSON.parse(element.hiddenData);

                    if (hiddenData.lockStatus == 1) {
                        showTips({content: "锁定的节目无法排序。", type: "error" });
                        setTimeout(function () {
                            jqGridTarget.restoreCell(iRow, iCol);
                        }, 50);
                        return;
                    }

                    var checkObj = {};
                    if (element.live !== "点播") {
                        checkObj.msg = "直播节目不支持索引调整";
                    } else if (element.startPlayTime < checkTime) {
                        checkObj.msg = "节目已播放完毕或正在播放中，不可修改。";
                    }
                    if (checkObj.msg != null) {
                        showTips({content: checkObj.msg, type: "error" });
                        setTimeout(function () {
                            jqGridTarget.restoreCell(iRow, iCol);
                        }, 50);
                    } else {
                        setTimeout(function () {
                            jqGridTarget.find("#" + rowid).find("td:eq(" + iCol + ")").find("input").select();
                            // console.log(td.find());
                        }, 50);
                    }
                },
                beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
                    console.log(" beforeSaveCell ");
                },
                errorCell: function (serverresponse, status) {

                },
//                gridComplete: function () {
//                    if (lockFlag) {
//                        console.log(" current lock");
//                        return;
//                    }
//
//                },

                prmNames: {
                    page: "pageNo",
                    rows: "pageSize"
                },
                multiselect: true,
                mtype: "post",
                datatype: "local",
                height: 450,
                rowNum: listSize,
                caption: "节目单列表",
                colNames: ["序号", "奇谱ID", "节目名称", "内容类型", "所属专辑", "开始时间", "结束时间", "播放类型", "节目类型", "付费状态", "更新日期", "隐藏数据", "操作"],
                colModel: [
                    {
                        name: "index",
                        index: 'index',
                        title: false,
                        width: 80,
                        sortable: false,
                        align: "center",
                        editable: true,
                        edittype: "text",
                        editrules: {
                            custom: true,
                            custom_func: function (value, colName) {
                                if (!/^[1-9]\d*$/.test(value)) {
                                    return [false, "请输入正整数"];
                                }
                                var obj = _jqGrid.jqGrid("getRowData");
                                if (parseInt(value, 10) > obj.length) {
                                    return [false, "长度越界"];
                                }
                                console.log("editrules excute");
                                //Carousel.
                                return [true, ""];
                            }
                        }
                    },
                    {
                        name: "qipuId",
                        index: 'qipuId',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var plusUrl = Carousel.urlConfig.getQiPuBaseUrl(cellvalue);
                            var colorPart = $("<em>&nbsp;&nbsp;</em>");
                            if (currentClient >= rowObject.startPlayTime && currentClient <= rowObject.endPlayTime) {
                                colorPart.addClass("current");
                            } else {
                                if (rowObject.startPlayTime.substr(11) >= "12:00:00") {
                                    colorPart.addClass("afternoon");
                                } else {
                                    colorPart.addClass("morning");
                                }
                            }
                            var cellEnd = cellvalue < 1 ? cellvalue : "<a target='_blank' href='" + plusUrl + "'>" + cellvalue + "</a>"
                            return  colorPart.prop("outerHTML") + cellEnd;
                        }
                    } ,
                    {
                        name: "pname",
                        index: 'pname',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var retValue = cellvalue;
                            if (rowObject.pageUrl != null) {
                                retValue = "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>";
                            }
                            if (rowObject.qipuId == 0 && rowObject.live == 1 && retValue.indexOf("delete") != -1) {
                                retValue = "<span style='color: red'>" + retValue + "</span>"
                            }
                            return retValue;
                        }
                    },
                    {
                        name: "referContentType",
                        index: 'referContentType',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue == null) {
                                return ""
                            }
                            var response = Carousel.Dao.getContentType();
                            var ret = cellvalue;
                            $.each(response.data, function (index, element) {
                                if (cellvalue == element.val) {
                                    ret = element.descr;
                                    return true;
                                }
                            })
                            return ret;
                        }
                    },
                    {
                        name: "albumName",
                        index: 'albumName',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "startPlayTime",
                        index: 'startPlayTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "endPlayTime",
                        index: 'endPlayTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "live",
                        index: 'live',
                        title: false,
                        width: 100,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            if (cellvalue == null) {
                                return "";
                            } else if (cellvalue == 0) {
                                return "未设置"
                            } else if (cellvalue == 1) {
                                return "点播"
                            } else if (cellvalue == 2) {
                                return "直播"
                            }
                        }
                    },
                    {
                        name: "type",
                        index: 'type',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var ret = []
                            var enumNameData = Carousel.Dao.liveProgramType();
                            $.each(enumNameData.data, function (index, element) {
                                if (cellvalue == element.key) {
                                    ret = element.descr;
                                    return true;
                                }
                            })
                            return ret
                        }
                    }
                    ,
                    {
                        name: "bossStatus",
                        index: 'bossStatus',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var enumValue = "";
                            switch (cellvalue) {
                                case "FREE":
                                    enumValue = "免费";
                                    break;
                                case "PAIED_NOT_AVAILABLE":
                                    enumValue = "付费未划价";
                                    break;
                                case "PAIED_AVAILABLE":
                                    enumValue = "付费已划价";
                                    break;
                                default:
                                    break;
                            }
                            return enumValue;
                        }
                    }
                    ,
                    {
                        name: "updateTime",
                        index: 'updateTime',
                        title: false,
                        width: 120,
                        sortable: false,
                        align: "center"
                    },
                    {
                        name: "hiddenData",
                        index: "hiddenData",
                        title: false,
                        hidden: true,
                        formatter: function (cellvalue, options, rowObject) {
                            var data = {};
                            if (typeof rowObject.lockStatus == 'undefined') {
                                rowObject.lockStatus = 0;
                            }

                            data.lockStatus = rowObject.lockStatus;
                            return JSON.stringify(data);
                        }
                    },
                    {
                        title: false,
                        width: 230,
                        sortable: false,
                        align: "center",
                        formatter: function (cellvalue, options, rowObject) {
                            var checkDate = new Date();
                            checkDate.setTime(checkDate.getTime() + 30 * 1000 * 60);
                            var checkTime = Carousel.Formatter.formatDate(checkDate);
                            var retOperation = "";
                            //rowObject.lockStatus = 1;   // TODO remove after testing
                            if (checkTime > rowObject.startPlayTime) {
                                retOperation += "<a class='disabled'>编目</a>&nbsp;" + getBroadcastControl(rowObject) + "<a class='disabled'>删除</a>&nbsp;";
                                if (rowObject.live != 2) {
                                    retOperation += "<a class='disabled'>上移</a>&nbsp;<a class='disabled'>下移</a>&nbsp;";
                                    if (rowObject.lockStatus == 1) {
                                        retOperation += "<a class='disabled'>解锁</a>";
                                    } else {
                                        retOperation += "<a class='disabled'>锁定</a>";
                                    }
                                }

                            } else {
                                retOperation += "<a href='javascript:;' onclick='Carousel.Operation.programEdit(" + rowObject.id + ")'>编目</a>  " +
                                    getBroadcastControl(rowObject) +
                                    "<a href='javascript:;' onclick='Carousel.Operation.programDel(" + rowObject.id + ")'>删除</a>  ";
                                if (rowObject.live != 2) {
                                    if (rowObject.lockStatus == 1) {
                                        retOperation += "<a class='disabled'>上移</a>&nbsp;<a class='disabled'>下移</a>  ";
                                        retOperation += "<a href='javascript:;' onclick='Carousel.Operation.programToggleLock(" + rowObject.id + ", 0)'>解锁</a>  ";
                                    } else {
                                        retOperation += "<a href='javascript:;' onclick='Carousel.Operation.programMoveUp(" + rowObject.id + ")'>上移</a>  " +
                                            "<a href='javascript:;' onclick='Carousel.Operation.programMoveDown(" + rowObject.id + ")'>下移</a>  "
                                        retOperation += "<a href='javascript:;' onclick='Carousel.Operation.programToggleLock(" + rowObject.id + ", 1)'>锁定</a>  ";
                                    }

                                }
                            }
                            return retOperation;
                        }
                    }
                ],
                pager: "#pager",
                toolbar: [true, "top"]
            });
            $("<span style='color:#187ddb'>直播视频只能回看二天！</span>").appendTo($("#t_list"));
            var bdiv = $(".ui-jqgrid-bdiv");

            $("<label style='width: 40px;float:right;'>PM</label>").bind("click", function () {
                if (bdiv[0].scrollHeight <= bdiv[0].clientHeight) {
                    return;
                }
                var allDate = $("#list").jqGrid("getRowData");
                var checkPM = "";
                var interrupt = 0;
                for (var i = 0; i < allDate.length; i++) {
                    checkPM = allDate[i].startPlayTime.substr(11);
                    if (checkPM >= "12:00:00") {
                        interrupt = i;
                        break;
                    }
                }
                bdiv.scrollTop(interrupt / allDate.length * bdiv[0].scrollHeight)
            }).appendTo($("#t_list"));
            $("<label style='width: 40px;float:right;'>AM</label>").bind("click", function () {
                bdiv.scrollTop(0)
            }).appendTo($("#t_list"));
            _jqGrid.jqGrid('navGrid', "#pager", { edit: false, add: false, del: false, search: false, refresh: false});
            _jqGrid.jqGrid('navButtonAdd', "#pager", {caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                onClickButton: function () {
                    console.log("self del");
                    var gridElement = $("#list");
                    var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                    var ids = [];
                    $.each(selectedtrArr, function (i, element) {
                        ids.push(parseInt($(element).attr("id")));
                    })
                    Carousel.Operation.programBatchDel(ids);
                }, position: "last", title: "批量删除", cursor: "pointer"});
//            _jqGrid.jqGrid('navGrid', "#pager", { edit: false, add: false, del: false, search: false, refresh: false,
//                delfunc: function (obj) {
//                    console.log("self del");
//                    Carousel.Operation.programBatchDel(obj)
//
//                }
//            });
        }

        function updateProgramListByDate(toDate) {
            if (toDate != null) {
                Carousel.memo.dataTime = toDate;
            }
            var lDateFormat = Carousel.memo.dataTime;
            var sendObj = {startDate: lDateFormat + " 00:00:00", endDate: lDateFormat + " 23:59:59", fatherId: Carousel.memo.fatherId}
            fillProgramListGrid(sendObj);
        }

        function fillProgramListGrid(sendObj) {
            lockFlag = true;
            var jqGridTarget = $("#list");
            jqGridTarget.clearGridData();
            lockFlag = false;
            jqGridTarget.find(".norecords").hide();
            $("#list").setGridParam({url: Carousel.urlConfig.programList, loadtext: '加载中...',
                loadui: "block", datatype: "json", postData: sendObj}).trigger("reloadGrid");
        }

        function initGrid() {
            initProgramListGrid();
        }

        return {
            initGrid: initGrid,
            updateProgramListByDate: updateProgramListByDate,
            fillProgramListGrid: fillProgramListGrid,
            setColorTime: setColorTime,
            gridSort: gridSort
        }
    })();
})
WeekManager = (function () {
    var focusStartTime = null;
    var weekday = new Array(7);
    weekday[0] = "星期日";
    weekday[1] = "星期一";
    weekday[2] = "星期二";
    weekday[3] = "星期三";
    weekday[4] = "星期四";
    weekday[5] = "星期五";
    weekday[6] = "星期六";

    function preWeek() {
        if (focusStartTime != null) {
            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
        }
    }

    function nextWeek() {
        if (focusStartTime != null) {
            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
        }
    }

    function updateWeek(startTime) {
        if (startTime != null) {
            focusStartTime = startTime;
        }
        var tempStartTime = new Date(focusStartTime.getTime());
        $("#dayRange div label").each(function (i, element) {
            var lDateFormat = Carousel.Formatter.quickDateFormat(tempStartTime);
            $(element).attr("query-date", lDateFormat);
            $(element).removeClass("selected");
            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
            if (lDateFormat == Carousel.memo.dataTime) {
                $(element).addClass("selected");
            }
            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
        })
    }

    function quickToCurrentWeek(flag) {
        var current = new Date();
        var currentIndex = -1;
        if (current.getDay() == 0) {
            currentIndex = 6;
        } else {
            currentIndex = current.getDay() - 1;
        }
        Carousel.memo.dataTime = Carousel.Formatter.quickDateFormat(current)
        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
        if (flag != null && !flag) {
            return;
        }
        Carousel.Grid.updateProgramListByDate(Carousel.memo.dataTime);
    }

    function bindEvent() {
        var weekRangeLabel = $("#weekRange label");
        $(weekRangeLabel[0]).bind("click", function () {
            WeekManager.preWeek();
        });
        $(weekRangeLabel[1]).bind("click", function () {
            WeekManager.quickToCurrentWeek();
        })
        $(weekRangeLabel[2]).bind("click", function () {
            WeekManager.nextWeek()
        })

        $("button.left").bind("click", function () {
            WeekManager.preWeek()
        })

        $("button.right").bind("click", function () {
            WeekManager.nextWeek()
        })
        $("#dayRange div label").bind("click", function (event) {
            var aChild = event.currentTarget;
            $(aChild).parent().find("label").removeClass("selected");
            $(aChild).addClass("selected");
            Carousel.Grid.updateProgramListByDate(aChild.getAttribute("query-date"))
        })
    }

    return{
        preWeek: preWeek,
        nextWeek: nextWeek,
        quickToCurrentWeek: quickToCurrentWeek,
        bindEvent: bindEvent
    }
})()
$(document).ready(function () {
    Carousel.DialogManager.initDialogs();
    Carousel.Grid.initGrid();
    Carousel.ajaxManager.afterLoadComplete(function () {
        var channelData = Carousel.Dao.getChannel();
        if (channelData.liveType != 3) {
            showTips({content: "当前频道不是轮播台", type: "error"});
            setTimeout(function () {
                window.location.href = "/epg/program_list.html?fatherId=" + Carousel.memo.fatherId;
            }, 2000)
            return;
        }
        WeekManager.bindEvent();
        $("button[name=btn_automation_rule]").hide();
        $("button[name=btn_auto_rule]").hide();
        if (channelData.automation == 1) {
            $("button[name=btn_automation_rule]").show();
        } else {
            $("button[name=btn_auto_rule]").show();
        }
        Carousel.DialogManager.initDialogCall();
        Carousel.Grid.updateProgramListByDate()
    })
    Carousel.memo.dataTime = Carousel.Formatter.quickDateFormat(new Date())
    WeekManager.quickToCurrentWeek(false);

    var taskArr = [];
    taskArr.push(Carousel.Task.getLiveProgramTypeTask());
    taskArr.push(Carousel.Task.getContentTypeTask());
    var fatherId = Com.url.getParameter("fatherId")
    if (fatherId != null) {
        Carousel.memo.fatherId = parseInt(fatherId);
        taskArr.push({regName: Carousel.memo.getChannel, options: {
            type: "post",
            url: Carousel.urlConfig.channelGet,
            dataType: "json",
            data: {id: fatherId}
        } });
    }
    $.each(taskArr, function (i, elementTask) {
        Carousel.ajaxManager.push(elementTask.regName, elementTask.options);
    })
    Carousel.ajaxManager.startLoad();
})
